<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前端代理测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .section {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }
        .result {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
            max-height: 300px;
            overflow-y: auto;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            margin: 5px 0;
            box-sizing: border-box;
        }
        .status {
            padding: 5px;
            margin: 5px 0;
            border-radius: 3px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .info {
            background-color: #d9edf7;
            color: #31708f;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>前端代理测试页面</h1>
        <p class="info">这个页面用于测试前端代理是否正确工作，以及前端是否能正确处理后端的流式响应。</p>
        
        <div class="section">
            <h2>直接测试后端API</h2>
            <button onclick="testDirectAPI()">直接测试后端API</button>
            <div id="direct-result" class="result"></div>
        </div>
        
        <div class="section">
            <h2>通过前端代理测试</h2>
            <button onclick="testProxyAPI()">通过前端代理测试</button>
            <div id="proxy-result" class="result"></div>
        </div>
        
        <div class="section">
            <h2>聊天API测试</h2>
            <div>
                <label for="session-id">会话ID:</label>
                <input type="text" id="session-id" value="test-session-123">
            </div>
            <div>
                <label for="message">消息:</label>
                <textarea id="message" rows="3">你好，这是一个测试消息</textarea>
            </div>
            <div>
                <button onclick="testDirectChat()">直接测试聊天API</button>
                <button onclick="testProxyChat()">通过代理测试聊天API</button>
            </div>
            <div id="chat-status" class="status"></div>
            <div id="chat-result" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://127.0.0.1:8001';
        const PROXY_BASE_URL = ''; // 使用前端代理
        
        // 测试直接访问后端API
        async function testDirectAPI() {
            const resultDiv = document.getElementById('direct-result');
            resultDiv.textContent = '正在测试...';
            
            try {
                const response = await fetch(`${API_BASE_URL}/`);
                const data = await response.json();
                
                resultDiv.textContent = `状态码: ${response.status}\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `错误: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        // 测试通过前端代理访问后端API
        async function testProxyAPI() {
            const resultDiv = document.getElementById('proxy-result');
            resultDiv.textContent = '正在测试...';
            
            try {
                // 注意：这里使用相对路径，会通过前端代理
                const response = await fetch(`/`);
                const data = await response.json();
                
                resultDiv.textContent = `状态码: ${response.status}\n${JSON.stringify(data, null, 2)}`;
                resultDiv.className = 'result success';
            } catch (error) {
                resultDiv.textContent = `错误: ${error.message}`;
                resultDiv.className = 'result error';
            }
        }
        
        // 测试直接访问聊天API
        async function testDirectChat() {
            await testChatAPI(API_BASE_URL, 'direct');
        }
        
        // 测试通过前端代理访问聊天API
        async function testProxyChat() {
            await testChatAPI(PROXY_BASE_URL, 'proxy');
        }
        
        // 通用聊天API测试函数
        async function testChatAPI(baseUrl, type) {
            const sessionId = document.getElementById('session-id').value;
            const message = document.getElementById('message').value;
            
            const statusDiv = document.getElementById('chat-status');
            const resultDiv = document.getElementById('chat-result');
            
            statusDiv.textContent = `正在通过${type === 'direct' ? '直接连接' : '代理'}发送消息...`;
            statusDiv.className = 'status info';
            resultDiv.textContent = '';
            
            const requestBody = {
                session_id: sessionId,
                message: message,
                use_rag: false,
                use_tools: false,
                stream: true
            };
            
            try {
                // 构建URL
                const chatUrl = type === 'direct' 
                    ? `${baseUrl}/v1/chat/` 
                    : `/v1/chat/`; // 使用代理时使用相对路径
                    
                const response = await fetch(chatUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}, message: ${await response.text()}`);
                }
                
                // 处理流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                
                statusDiv.textContent = `通过${type === 'direct' ? '直接连接' : '代理'}接收流式响应...`;
                statusDiv.className = 'status success';
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        statusDiv.textContent = `通过${type === 'direct' ? '直接连接' : '代理'}的流式响应完成`;
                        break;
                    }
                    
                    buffer += decoder.decode(value, { stream: true });
                    
                    // 处理SSE事件
                    while (true) {
                        const newlineIndex = buffer.indexOf('\n\n');
                        if (newlineIndex === -1) break;
                        
                        const eventData = buffer.substring(0, newlineIndex);
                        buffer = buffer.substring(newlineIndex + 2);
                        
                        if (eventData.startsWith('data: ')) {
                            const dataContent = eventData.substring(6);
                            try {
                                const parsed = JSON.parse(dataContent);
                                if (parsed.type === 'chunk' && parsed.content) {
                                    resultDiv.textContent += parsed.content;
                                } else if (parsed.type === 'error') {
                                    statusDiv.textContent = `错误: ${parsed.content}`;
                                    statusDiv.className = 'status error';
                                } else if (parsed.type === 'done') {
                                    statusDiv.textContent = `通过${type === 'direct' ? '直接连接' : '代理'}的流式响应完成`;
                                }
                            } catch (e) {
                                console.error('解析SSE数据失败:', e, dataContent);
                                resultDiv.textContent += dataContent + '\n';
                            }
                        }
                    }
                }
            } catch (error) {
                statusDiv.textContent = `错误: ${error.message}`;
                statusDiv.className = 'status error';
            }
        }
        
        // 页面加载时自动测试
        window.onload = function() {
            testDirectAPI();
            testProxyAPI();
        };
    </script>
</body>
</html>